#include "my_timer.h"
#include "global.h"

extern unsigned                     g_TimerIndex;
extern map<unsigned,TimerStruct>   *g_pTimerMap;

BSTimer::BSTimer()
{
    g_TimerIndex++;
    m_id  = g_TimerIndex;
    m_cmd = 0;
    m_pTimerHanle = NULL;
}

BSTimer::~BSTimer()
{
    stopTimer();
}

void BSTimer::setHandle(int cmd , TimerHandle* pHandle)
{
    m_cmd = cmd;
    m_pTimerHanle = pHandle;
}

int BSTimer::startTimer(int seconds)
{
    map<unsigned,TimerStruct>::iterator iter = g_pTimerMap->find(m_id);
    if( iter != g_pTimerMap->end() ) {
        TimerStruct &Timer = iter->second;
        if( Timer.timer != NULL ) {
            return -1;
        }
        Timer.ExeTime   = time(NULL) + (time_t)seconds;
        Timer.timer     = this;
    } else {
        TimerStruct &Timer = (*g_pTimerMap)[m_id];
        Timer.ExeTime   = time(NULL) + (time_t)seconds;
        Timer.timer     = this;
    }

    return 0;
}

int BSTimer::stopTimer()
{
    TimerStruct &Timer = (*g_pTimerMap)[m_id];
    Timer.ExeTime   = -1;
    Timer.timer     = NULL;
    return 0;
}

void BSTimer::processTimer()
{
    if( m_pTimerHanle != NULL ) {
        m_pTimerHanle->processTimeOut(m_cmd);
    }
}
